package com.guomao.iodemos;

import java.io.*;

public class DemoC {

    public static void main(String[] args) {


//        String path = "data.txt";
//        String path = "data_gbk.txt";
        String path = "data_utf8.txt";

//        writeMyData(path);


        readMyData(path);

//        如果确认使用系统默认的UTF8读写文件 直接使用便捷类FileReader和FileWriter
//        如果需要切换使用其他编码格式 GBK BIG5 GB18030 选择使用InputStreamReader/OutputStreamWriter
    }

    private static void readMyData(String path) {

//        new FileReader("")

        try {
//            InputStreamReader isr = new InputStreamReader(new FileInputStream(path), "UTF-8");
//            InputStreamReader isr = new InputStreamReader(new FileInputStream(path), "GBK");
            InputStreamReader isr = new InputStreamReader(new FileInputStream(path));

            char[] buffer = new char[1024];

            int i = isr.read(buffer);

            String s = new String(buffer, 0, i);

            System.out.println(s);

            isr.close();

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
        }


    }

    private static void writeMyData(String path) {

        try {
//            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
//            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path), "GBK");
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path));

            osw.write("Hello 中国厦门");

            osw.flush();
            osw.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }


    }

}
